/*
 * IBM Corporation.
 * Copyright (c) 2014 All Rights Reserved.
 */

package com.ibm.iisp.common.dao;

import java.util.Date;

import javax.persistence.PrePersist;
import javax.persistence.PreRemove;
import javax.persistence.PreUpdate;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.context.SecurityContextHolder;

import com.ibm.iisp.common.vo.AuditVO;

/**
 * 类作用：用于自动设置审计信息
 * @author Johnny@cn.ibm.com
 * 使用说明：
 */
public class AuditListener {
	/**
	 * 
	 */
	private static final String CREATE = "create";
	/**
	 * 
	 */
	private static final String UPDATE = "update";
	private Logger log = LoggerFactory.getLogger(getClass());
	
	
	@PrePersist @PreUpdate
    private void prePersist(AuditVO object) {
		String action = UPDATE;
		if (object.getCreateTime() == null) {
			action = CREATE;
			object.setCreateTime(new Date());
			object.setCreateUser(getCurrentUserName());
		}
		object.setLastUpdateUser(object.getCreateUser());
		log.info("Object {} with id={} is {}d By {}", object.getClass(), object.getId(), action, getCurrentUserName());
	}

	@PreRemove
    private void preRemove(AuditVO object) { 
		log.info("Object {} with id={} Removed By {}", object.getClass(), object.getId(), getCurrentUserName());
	}
	
    private String getCurrentUserName(){
    	if (SecurityContextHolder.getContext() != null && SecurityContextHolder.getContext().getAuthentication() != null){
    		return SecurityContextHolder.getContext().getAuthentication().getName();
    	}
    	return null;
    }
}
